﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProgramShortcuts.Components.Services;

namespace ProgramShortcuts.Components.Functions
{
	public class CalculatorFunctionState : IFunctionState
	{
		
		IWriteString _WriteString;
		IClearScreen _ClearScreen;
		List<string> _Digits;
		public CalculatorFunctionState( 
			IClearScreen clearScreen,
			IWriteString writeString )
				
			{
				_ClearScreen = clearScreen;
				_WriteString = writeString;
			}
			public void InteractWithUser( ConsoleKeyInfo consoleKeyInfo )
			{
				if ( consoleKeyInfo.Key == ConsoleKey.Enter )
				{
					_WriteString.Write( Environment.NewLine );
					_WriteString.Write( "equals to " );

					double result = 0.0;
					for ( int i = 0; i < _Digits.Count; i++ )
					{
						double d = 0.0;
						if ( !string.IsNullOrEmpty( _Digits[i] ) )
						{
							Double.TryParse( _Digits[i], out d );
						}
						result += d;
					}

					_WriteString.Write( string.Format( "{0:0.##}", result ) );
					_WriteString.Write( Environment.NewLine );
					
					InitializeDigitsList();
					InformUserOfCurrentState();
					
					return;
				}
				char pressedChar = consoleKeyInfo.KeyChar;
				if ( Char.IsDigit( pressedChar ) || '.' == pressedChar )
				{
					
					_Digits[_Digits.Count - 1] += consoleKeyInfo.KeyChar;
					_WriteString.Write( consoleKeyInfo.KeyChar.ToString() );
				}
				if ( Char.IsWhiteSpace( pressedChar ) )
				{
					if ( string.IsNullOrEmpty( _Digits[_Digits.Count - 1] ) ) _WriteString.Write( "0" );
					_WriteString.Write( " and " );
					_Digits.Add( "" );
				}


			}

			private void InitializeDigitsList()
			{
				_Digits = new List<string>();
				_Digits.Add( "" );
				
			}

			#region IFunctionstate Members


			public void InformUserOfCurrentState()
			{
				InitializeDigitsList();
				_ClearScreen.ClearCurrentLine();
				_WriteString.Write( "Calculator add " );
			}

			#endregion
	}
}
